package com.edu.edumanager.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.edu.edumanager.bean.EduSubject;
import com.edu.edumanager.exception.EduException;
import com.edu.edumanager.mapper.EduSubjectMapper;
import com.edu.edumanager.vo.ExcelVo;

import java.util.Date;
import java.util.Map;

/**
 * @program: edu-manager
 * @description:
 * @author: Jaime
 * @create: 2021-08-13 11:51
 **/
public class ExcelListener extends AnalysisEventListener {
    //当我们new对象以后  这个eduSubjectMapper对象有值了
    //默认值为 null
    private EduSubjectMapper eduSubjectMapper;

    //这个是一个构造方法 new对象的时候执行这个构造方法
    public ExcelListener(EduSubjectMapper eduSubjectMapper) {
        this.eduSubjectMapper = eduSubjectMapper;
    }

    /** easyExcel invoke 方法 默认循环行读取
     * 一行一行读取数据,插入数据库
     * @param o
     * @param analysisContext
     */
    @Override
    public void invoke(Object o, AnalysisContext analysisContext) {
        ExcelVo excelVo = (ExcelVo) o;
        if (excelVo == null) {
            throw new EduException("文件格式错误");
        }
        EduSubject eduSubject = eduSubjectMapper.findSubjectByName(excelVo.getOneName());
        if (eduSubject == null) {

            eduSubject = new EduSubject();
            eduSubject.setTitle(excelVo.getOneName());
            eduSubject.setParentId(0);
            eduSubject.setSort(1);
            Date date = new Date();
            eduSubject.setGmtCreate(date);
            eduSubject.setGmtModified(date);
            int row = eduSubjectMapper.addSubject(eduSubject);
            if (row == 0) {
                throw new EduException("插入课程失败");
            }
        }
        EduSubject eduSubjectTwo = eduSubjectMapper.findSubjectByName(excelVo.getTwoName());
        if (eduSubjectTwo==null){
            eduSubjectTwo = new EduSubject();
            eduSubjectTwo.setTitle(excelVo.getTwoName());
            eduSubjectTwo.setParentId(eduSubject.getId());
            eduSubjectTwo.setSort(1);
            Date date = new Date();
            eduSubjectTwo.setGmtCreate(date);
            eduSubjectTwo.setGmtModified(date);
            int row = eduSubjectMapper.addSubject(eduSubjectTwo);
            if (row == 0) {
                throw new EduException("插入课程失败");
            }
        }


        // System.out.println("****" +eduSubject.toString());
        // EduSubject eduSubject = eduSubjectMapper.findSubjectByName(excelVo.getOneName());

    }

    @Override
    public void invokeHeadMap(Map headMap, AnalysisContext context) {
        System.out.println(headMap + "--------------------------");
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        System.out.println("读取完了");
    }
}
